import * as THREE from 'three';
import { Vec3 } from '@/core/types';
import { HostileEntity } from './HostileEntity';
import { EntityType, EntityStats } from './types';
import { WorldManager } from '@/world/WorldManager';
import { ItemDropManager } from '@/world/ItemDrop';
import { BlockType } from '@/blocks/types';
import { getAudioManager } from '@/audio/AudioManager';

export class Skeleton extends HostileEntity {
  private shootCooldown = 0;
  private shootInterval = 2.0; // 2秒射击间隔
  private arrows: THREE.Object3D[] = [];

  constructor(id: string, position: Vec3, worldManager: WorldManager, itemDropManager?: ItemDropManager) {
    const stats: EntityStats = {
      maxHealth: 20,
      moveSpeed: 1.2,
      jumpHeight: 1.0,
      attackDamage: 4,
      attackRange: 8, // 远程攻击距离更远
      detectionRange: 16,
      size: { width: 0.6, height: 1.8 }
    };

    super(id, EntityType.SKELETON, position, worldManager, stats, itemDropManager);
  }

  protected createMesh(): void {
    // 创建一个简单的骷髅模型
    const group = new THREE.Group();

    // 身体
    const bodyGeometry = new THREE.BoxGeometry(0.6, 1.2, 0.3);
    const bodyMaterial = new THREE.MeshLambertMaterial({ color: 0xF5F5DC }); // 米白色
    const body = new THREE.Mesh(bodyGeometry, bodyMaterial);
    body.position.set(0, 0.6, 0);
    group.add(body);

    // 头部（骷髅头）
    const headGeometry = new THREE.BoxGeometry(0.5, 0.5, 0.5);
    const headMaterial = new THREE.MeshLambertMaterial({ color: 0xFFFFF0 }); // 象牙白
    const head = new THREE.Mesh(headGeometry, headMaterial);
    head.position.set(0, 1.45, 0);
    group.add(head);

    // 眼窝（黑色）
    const eyeGeometry = new THREE.BoxGeometry(0.08, 0.08, 0.1);
    const eyeMaterial = new THREE.MeshLambertMaterial({ color: 0x000000 });
    
    const leftEye = new THREE.Mesh(eyeGeometry, eyeMaterial);
    leftEye.position.set(-0.1, 1.5, -0.24);
    group.add(leftEye);
    
    const rightEye = new THREE.Mesh(eyeGeometry, eyeMaterial);
    rightEye.position.set(0.1, 1.5, -0.24);
    group.add(rightEye);

    // 手臂
    const armGeometry = new THREE.BoxGeometry(0.2, 0.8, 0.2);
    const armMaterial = new THREE.MeshLambertMaterial({ color: 0xF5F5DC });
    
    const leftArm = new THREE.Mesh(armGeometry, armMaterial);
    leftArm.position.set(-0.5, 0.8, 0);
    group.add(leftArm);
    
    const rightArm = new THREE.Mesh(armGeometry, armMaterial);
    rightArm.position.set(0.5, 0.8, 0);
    group.add(rightArm);

    // 弓（简化版）
    const bowGeometry = new THREE.BoxGeometry(0.05, 0.6, 0.05);
    const bowMaterial = new THREE.MeshLambertMaterial({ color: 0x8B4513 }); // 棕色
    const bow = new THREE.Mesh(bowGeometry, bowMaterial);
    bow.position.set(-0.6, 0.8, 0);
    bow.rotation.z = Math.PI / 4;
    group.add(bow);

    // 腿部
    const legGeometry = new THREE.BoxGeometry(0.2, 0.8, 0.2);
    const legMaterial = new THREE.MeshLambertMaterial({ color: 0xF5F5DC });
    
    const leftLeg = new THREE.Mesh(legGeometry, legMaterial);
    leftLeg.position.set(-0.15, -0.4, 0);
    group.add(leftLeg);
    
    const rightLeg = new THREE.Mesh(legGeometry, legMaterial);
    rightLeg.position.set(0.15, -0.4, 0);
    group.add(rightLeg);

    // 添加一些骨头细节
    const boneGeometry = new THREE.CylinderGeometry(0.02, 0.02, 0.3);
    const boneMaterial = new THREE.MeshLambertMaterial({ color: 0xFFFFF0 });
    
    // 肋骨
    for (let i = 0; i < 4; i++) {
      const rib = new THREE.Mesh(boneGeometry, boneMaterial);
      rib.position.set(0, 0.8 - i * 0.15, -0.16);
      rib.rotation.z = Math.PI / 2;
      group.add(rib);
    }

    // 设置阴影
    group.traverse((child) => {
      if (child instanceof THREE.Mesh) {
        child.castShadow = true;
        child.receiveShadow = true;
      }
    });

    this.mesh = group;
  }

  protected onAttack(): void {
    // 检查射击冷却
    if (this.shootCooldown > 0) {
      return;
    }

    // 骷髅射箭攻击
    console.log(`Skeleton ${this.id} shoots an arrow!`);
    
    if (this.target) {
      this.shootArrow(this.target);
    }
    
    // 设置射击冷却
    this.shootCooldown = this.shootInterval;
    
    // 射击动画（拉弓）
    if (this.mesh) {
      const rightArm = this.mesh.children[5]; // 右臂
      if (rightArm) {
        const originalRotation = rightArm.rotation.x;
        rightArm.rotation.x = -Math.PI / 3; // 拉弓姿势
        
        // 0.5秒后恢复
        setTimeout(() => {
          if (rightArm) {
            rightArm.rotation.x = originalRotation;
          }
        }, 500);
      }
    }
  }

  private shootArrow(target: Vec3): void {
    if (!this.mesh || !this.mesh.parent) return;

    // 创建箭矢
    const arrowGeometry = new THREE.CylinderGeometry(0.02, 0.02, 0.5);
    const arrowMaterial = new THREE.MeshLambertMaterial({ color: 0x8B4513 });
    const arrow = new THREE.Mesh(arrowGeometry, arrowMaterial);
    
    // 设置箭矢起始位置
    arrow.position.copy(this.mesh.position);
    arrow.position.y += 1.2; // 从胸部高度射出
    
    // 计算射击方向
    const direction = new THREE.Vector3(
      target.x - this.position.x,
      target.y - this.position.y + 0.5, // 稍微向上瞄准
      target.z - this.position.z
    ).normalize();
    
    // 设置箭矢朝向
    arrow.lookAt(
      arrow.position.x + direction.x,
      arrow.position.y + direction.y,
      arrow.position.z + direction.z
    );
    
    // 添加到场景
    this.mesh.parent.add(arrow);
    this.arrows.push(arrow);
    
    // 箭矢飞行动画
    this.animateArrow(arrow, direction);
  }

  private animateArrow(arrow: THREE.Object3D, direction: THREE.Vector3): void {
    const speed = 15; // 箭矢速度
    const gravity = -9.8;
    let velocity = direction.clone().multiplyScalar(speed);
    let time = 0;
    
    const animate = () => {
      time += 0.016; // 约60fps
      
      // 应用重力
      velocity.y += gravity * 0.016;
      
      // 更新位置
      arrow.position.add(velocity.clone().multiplyScalar(0.016));
      
      // 更新朝向
      arrow.lookAt(
        arrow.position.x + velocity.x,
        arrow.position.y + velocity.y,
        arrow.position.z + velocity.z
      );
      
      // 检查是否击中地面或飞行时间过长
      if (arrow.position.y <= 0 || time > 3) {
        // 移除箭矢
        if (arrow.parent) {
          arrow.parent.remove(arrow);
        }
        
        // 从数组中移除
        const index = this.arrows.indexOf(arrow);
        if (index > -1) {
          this.arrows.splice(index, 1);
        }
        
        // 清理资源
        if (arrow instanceof THREE.Mesh) {
          arrow.geometry.dispose();
          if (Array.isArray(arrow.material)) {
            arrow.material.forEach(mat => mat.dispose());
          } else {
            arrow.material.dispose();
          }
        }
      } else {
        requestAnimationFrame(animate);
      }
    };
    
    animate();
  }

  protected dropLoot(): void {
    // 骷髅死亡时掉落骨头和箭
    console.log(`Skeleton ${this.id} dropped bones and arrows`);
    
    if (this.itemDropManager) {
      // 掉落骨头 (0-2个)
      const boneCount = Math.floor(Math.random() * 3);
      if (boneCount > 0) {
        this.itemDropManager.dropItem(BlockType.BONE, boneCount, this.position);
      }
      
      // 掉落箭 (0-2个)
      const arrowCount = Math.floor(Math.random() * 3);
      if (arrowCount > 0) {
        this.itemDropManager.dropItem(BlockType.ARROW, arrowCount, this.position);
      }
      
      // 小概率掉落弓
      if (Math.random() < 0.025) { // 2.5%概率
        console.log(`Skeleton ${this.id} dropped a bow!`);
        this.itemDropManager.dropItem(BlockType.BOW, 1, this.position);
      }
    }
  }

  public update(deltaTime: number): void {
    super.update(deltaTime);
    
    // 更新射击冷却
    if (this.shootCooldown > 0) {
      this.shootCooldown -= deltaTime;
    }
    
    // 添加骷髅特有的行为
    this.addSkeletonBehavior(deltaTime);
  }

  private addSkeletonBehavior(deltaTime: number): void {
    // 骷髅会保持距离进行远程攻击
    if (this.ai?.state === 'attacking' && this.target) {
      const distance = this.getDistanceTo(this.target);
      
      // 如果太近，后退
      if (distance < 4) {
        const retreatDirection = {
          x: this.position.x - this.target.x,
          y: 0,
          z: this.position.z - this.target.z
        };
        const retreatDistance = Math.sqrt(retreatDirection.x ** 2 + retreatDirection.z ** 2);
        
        if (retreatDistance > 0) {
          retreatDirection.x /= retreatDistance;
          retreatDirection.z /= retreatDistance;
          
          this.velocity.x = retreatDirection.x * this.stats.moveSpeed;
          this.velocity.z = retreatDirection.z * this.stats.moveSpeed;
        }
      }
    }

    // 骨头咔嗒声（简化版）
    if (Math.random() < 0.002) {
      console.log(`Skeleton ${this.id}: *rattle*`);
      const audioManager = getAudioManager();
      audioManager.playSound('skeleton_idle', {
        position: this.position,
        volume: 0.5
      });
    }

    // 在阳光下受伤（简化版）
    if (Math.random() < 0.001) {
      // this.takeDamage(1);
      console.log(`Skeleton ${this.id} is burning in sunlight!`);
    }
  }

  // 重写攻击间隔检查
  protected processAI(deltaTime: number): void {
    super.processAI(deltaTime);
    
    // 更新射击冷却
    if (this.shootCooldown > 0) {
      this.shootCooldown -= deltaTime;
    }
  }



  // 清理资源时也要清理箭矢
  public dispose(): void {
    // 清理所有箭矢
    this.arrows.forEach(arrow => {
      if (arrow.parent) {
        arrow.parent.remove(arrow);
      }
      if (arrow instanceof THREE.Mesh) {
        arrow.geometry.dispose();
        if (Array.isArray(arrow.material)) {
          arrow.material.forEach(mat => mat.dispose());
        } else {
          arrow.material.dispose();
        }
      }
    });
    this.arrows = [];
    
    super.dispose();
  }
}